/**
 * Copyright (C) 2009+ Spark Zheng
 *
 * @file        test/test_tcp_client.c 
 * @date        2010-05-16
 * @brief	test_module
 *		create a tcp client
 * @see         dserver
 * @history
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <dlib/log.h>
#include <dlib/str.h>

#include "libdserver.h"

#define TEST_LOOP	10
#define TEST_BUF_LEN	1024

static char *test_str[TEST_LOOP] = {
	"test1",
	"test2",
	"test3",
	"test4",
	"test5",
	"test6",
	"test7",
	"test8",
	"test9",
	"testA"
};

int main(int argc, char **argv)
{
	if (argc < 3) {
		fprintf(stderr, "USAGE: test_tcp_client ip port\n");
		return -1;
	}

	int ret = 0;
	const char *ip = argv[1];
	in_port_t port = (in_port_t)atoi(argv[2]);

	char buf[TEST_BUF_LEN + 1] = {0};

	int j;
	int sfd;

	for (j = 0; j < 10000; j++) {

		fprintf(stderr, "build up tcp client to ip:%s, port:%u.\n", ip, port);
		sfd = dserver_tcpclient_init(ip, port, 30);
		if (sfd < 0) {
			fprintf(stderr, "create tcpclient error, ip[%s]:port[%d].\n", ip, port);
			return -2;
		}

		int i;
		int k;
		for (i = 0; i < TEST_LOOP * 100; i++) {
			k = i % TEST_LOOP;
			fprintf(stderr, "tcp write data[%s].\n", test_str[k]);
#if 0
			ret = write(sfd, test_str[k], strlen(test_str[k]));
#else
			ret = dserver_tcpdata_write(sfd, test_str[k], strlen(test_str[k]), 1);
#endif
			if (ret < 0) {
				fprintf(stderr, "tcp data write error[%d]:%s\n", ret, strerror(errno));
				continue;	
			}
#if 0
			ret = read(sfd, buf, TEST_BUF_LEN);
#else
			ret = dserver_tcpdata_read(sfd, buf, TEST_BUF_LEN, 1);
#endif
			if (ret < 0) {
				fprintf(stderr, "tcp data read error[%d]:%s.\n", ret, strerror(errno));
				continue;	
			}
			buf[ret] = 0;
			fprintf(stderr, "tcp read data[%s].\n", buf);
		}

		dserver_tcpclient_exit(sfd);
	}
 
	return 0;
}
